<template>
  <div>
    <el-form ref="form" :model="query" label-width="80px" :inline="true">
      <el-form-item>
        <el-date-picker
          v-model="query.date"
          placeholder="日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch()">搜索</el-button>
      </el-form-item>
    </el-form>

    <barchart :options="options" />
  </div>
</template>

<script>
import { ereport } from '@/api/equipment/index.js';
import moment from 'moment';
import barchart from '@/views/chart/components/barchart.vue';

export default {
  components: {
    barchart,
  },
  props: ['data'],
  watch: {
    data: {
      handler: function (val) {
        this.query.deviceid = val.deviceid;
        this.query.ln = val.ln;
        this.query.date = moment().format('YYYY-MM-DD');
        this.getData();
      },
      immediate: true,
    },
  },
  data() {
    return {
      query: {
        deviceid: '',
        ln:'',
        date: moment().format('YYYY-MM-DD'),
      },
      options: {},
      dateArr: [],
      dayRange: {},
      lnidArr: {},
      seriesData: {},
    };
  },
  methods: {
    getData() {
      ereport(this.query).then((res) => {
        this.dateArr = JSON.parse(res.data.dateArr);
        this.dayRange = res.data.dayRange;
        this.lnidArr = JSON.parse(res.data.lnidArr);
        this.seriesData = JSON.parse(res.data.seriesData);
        this.initChart();
      });
    },
    initChart() {
      const cols = [];
      Object.keys(this.lnidArr).forEach((key) => {
        cols.push(key + '路');
      });

      let series = this.convertSeries(this.seriesData);
      this.options = {
        xAxis: {
          type: 'category',
          data: this.dateArr,
          title: '时间段',
          // axisLabel: {
          //   formatter: function (value) {
          //     let arr = value.split('|');
          //     return arr[0] + '\n' + arr[1];
          //   },
          // },
        },
        yAxis: {
          type: 'value',
          name: '用电量(kwh)',
        },
        legend: {data: cols},
        series,
      };
    },
    convertSeries(seriesData) {
      let series = [];
        Object.values(seriesData).forEach(item => {

            series.push({
                name: item.name,
                type: 'bar',
                data: item.data,
                label: {
                    show: true,
                    position: 'top'
                },
            });
        });
        return series;
    },
    onSearch(){
      this.getData()
    }
  },
};
</script>

<style scoped></style>
